package register;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import enumeration.RpcError;
import exception.RpcException;
import loadbalance.LoadBalance;
import loadbalance.RobinLoadBalance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.NacosUtil;

import java.net.InetSocketAddress;
import java.util.List;

public class NacosServiceDisCovery implements ServiceDiscovery {

    private static final Logger logger = LoggerFactory.getLogger(NacosServiceDisCovery.class);

    private LoadBalance loadBalance;
    private final LoadBalance DEFAULT_LOAD_BALANCE = new RobinLoadBalance();

    public NacosServiceDisCovery(LoadBalance loadBalance) {
        this.loadBalance = loadBalance;
    }

    public NacosServiceDisCovery(){
        this.loadBalance = DEFAULT_LOAD_BALANCE;
    }

    @Override
    public InetSocketAddress lookUPService(String serviceName) {
        try {
            List<Instance> allInstances = NacosUtil.namingService.getAllInstances(serviceName);
            Instance instance = loadBalance.select(serviceName, allInstances);
            return new InetSocketAddress(instance.getIp(),instance.getPort());
        } catch (NacosException e) {
            logger.error("寻找服务失败",e);
            throw new RpcException(RpcError.SERVICE_NO_FOUND);
        }
    }
}
